package com.codes.core.common.validation;

import com.codes.core.common.result.Result;
import com.codes.core.common.result.ResultCode;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;

@RestControllerAdvice
public class ParamVerifyException {


    @ExceptionHandler(BindException.class)
    public Result ConstraintViolationException(BindException e) {
        // 从异常对象中拿到ObjectError对象
        List<ObjectError> errors =  e.getBindingResult().getAllErrors();
        StringBuffer sb = new StringBuffer();
        for (ObjectError error :errors) {
            sb.append(error.getDefaultMessage()+",");
        }
        String reMsg = sb.substring(0,sb.length()-1).toString();
        // 然后提取错误提示信息进行返回
        return  new Result(ResultCode.VALIDATE_FAILED,reMsg);
    }

//    @ExceptionHandler(APIException.class)
//    public Result APIExceptionHandler(APIException e) {
//        return  Result.failed(e.getMsg());
//       // return ApiResponse.failed("请求接口失败:"+e.getMsg());
//    }


}
